<template>
  <div class="flex justify-center items-center h-screen">
    <!-- 卡片内容 -->
    <AnnCard
        class="min-w-[800px]"
        custom-style="text-gray-600 font-bold"
        title="继续以完成第三方帐号绑定">
      <div class="mt-5">
        <div class="flex justify-center items-center">
          <!-- logo图片 -->
          <img src="../../assets/images/logo.png" width="40" height="40"/>
          <!-- 箭头 -->
          <Icon
              name="line-md:double-arrow-horizontal"
              size="35"
              class="text-gray-500 ml-4 mr-4"/>
          <!-- gitee图标 -->
          <Icon :name="socialLogo" color="#c71d23" size="40"/>
        </div>
        <div class="flex mt-6 justify-center items-center">
          你已通过<strong>{{ socialName }}</strong>
          授权，完善以下登录信息即可完成绑定
        </div>
        <div class="mt-10 w-80 mx-auto">
          <!-- 注册form -->
          <section
              v-if="showRegisterForm"
              class="flex flex-col justify-center items-center">
            <input
                type="text"
                placeholder="请输入邮箱"
                v-model="blogRegisterForm.email"
                class="input input-bordered input-warning w-full max-w-xs"/>
            <input
                type="password"
                placeholder="密码不小于5位"
                v-model="blogRegisterForm.password"
                class="input input-bordered input-warning w-full max-w-xs mt-5"/>
            <input
                type="password"
                v-model="blogRegisterForm.ensurePassword"
                placeholder="请再次确认密码"
                class="input input-bordered input-warning w-full max-w-xs mt-5"/>
            <div class="flex items-center mt-5">
              <input
                  type="input"
                  v-model="blogRegisterForm.code"
                  class="input input-bordered input-warning w-full"
                  placeholder="请输入验证码"/>
              <button
                  class="btn btn-outline w-28 ml-4"
                  :disabled="btnDisabled"
                  @click="getCode(blogRegisterForm.email, '1')">
                {{ btnText }}
              </button>
            </div>
            <button
                class="btn btn-lg btn-primary w-80 mt-5"
                @click="handleRegister">
              注册并绑定
            </button>
            <a class="link link-success no-underline mt-5" @click="showRegisterForm = !showRegisterForm">
              {{ showRegisterForm ? "已有帐号？ 点此绑定" : "没有账号？注册一个" }}</a>
          </section>
          <!-- 登录form -->
          <section v-else class="flex flex-col justify-center items-center">
            <input
                type="text"
                placeholder="请输入邮箱"
                class="input input-bordered input-warning w-full max-w-xs"
                v-model="blogLoginForm.email"
            />
            <input
                v-if="pwdLogin"
                type="password"
                placeholder="密码不小于5位"
                class="input input-bordered input-warning w-full max-w-xs mt-5"
                v-model="blogLoginForm.password"/>
            <div class="flex items-center mt-5" v-else>
              <input
                  type="input"
                  class="input input-bordered input-warning w-full"
                  placeholder="请输入验证码"
                  v-model="blogLoginForm.code"/>
              <button
                  class="btn btn-outline w-28 ml-4"
                  :disabled="btnDisabled"
                  @click="getCode(blogLoginForm.email, '0')">
                {{ btnText }}
              </button>
            </div>
            <div class="ml-auto mt-3">
              <a class="link link-success no-underline"
                 @click="pwdLogin = !pwdLogin">{{ pwdLogin ? "邮箱验证码绑定" : "账号密码绑定" }}</a>
            </div>
            <button
                class="btn btn-lg btn-primary w-80 mt-5"
                @click="handleLogin">
              登录并绑定已有账号
            </button>
            <a class="link link-success no-underline mt-5"
               @click="showRegisterForm = !showRegisterForm">{{
                showRegisterForm ? "已有帐号？ 点此绑定" : "没有账号？注册一个"
              }}</a>
          </section>
        </div>
      </div>
    </AnnCard>
  </div>
</template>

<script lang="ts" setup>
import type {BlogLoginForm, BlogRegisterForm, SendCodeBo} from "~/api/user/types";
import { sendCode} from "~/api/user";
import {useUserStore} from "~/store/user";
import {showMessage} from "~/utils/toast";
const route = useRoute();
const userStore = useUserStore();
defineProps({
  socialLogo: {
    default: "",
  },
  socialName: {
    default: "第三方",
  },
});
// 密码登录
const pwdLogin = ref(true);

const showRegisterForm = ref(false);
const btnDisabled = ref(false);
const btnText = ref("发送验证码");
const countDownSeconds = ref(60); // 剩余秒数
let countDownInterval: NodeJS.Timer; // 定时器
const blogLoginForm = reactive<BlogLoginForm>({
  email: "",
  password: "",
  code: "",
  source: "GITEE",
  socialCode: route.query.code as string,
  state: route.query.state as string,
});

const blogRegisterForm = reactive<BlogRegisterForm>({
  email: "",
  password: "",
  ensurePassword: "",
  code: "",
  source: "GITEE",
  socialCode: route.query.code as string,
  state: route.query.state as string,
});

const codeBo = reactive<SendCodeBo>({
  email: "",
  type: "",
});

// 校验
const validateForm = () => {
  if (pwdLogin.value && (!blogLoginForm.email || !blogLoginForm.password)) {
    blogLoginForm.code = undefined;
    showMessage("邮箱或密码不能为空", "danger");
    return false;
  }

  if (!pwdLogin.value && (!blogLoginForm.email || !blogLoginForm.code)) {
    showMessage("邮箱或密码不能为空", "danger");
    return false;
  }
  return true;
};
const handleLogin = async () => {
  if (!validateForm()) {
    return;
  }
  let loginType;
  if (pwdLogin.value) {
    blogLoginForm.code = undefined;
    loginType = "pwdLogin";
  } else {
    blogLoginForm.password = undefined;
    loginType = "emailCodeLogin";
  }
  await userStore.doLogin(blogLoginForm, loginType);
  showMessage("登录成功");
  // 在登录成功后执行跳转
  window.open("/", "_self");
};
const handleRegister = async () => {
  await userStore.doRegister(blogRegisterForm);
  showMessage("注册成功");
  // 在登录成功后执行跳转
  window.open("/", "_self");
};

// 发送验证码
const getCode = async (email: string, type: string) => {
  codeBo.email = email;
  codeBo.type = type;
  const {data: res} = await useAsyncData("sendCode", () => sendCode(codeBo));
  if (res.value?.code == 200) {
    showMessage("发送成功");
    btnDisabled.value = true;
    // 开始倒计时
    startCountDown();
  }
};

// 开始倒计时函数
const startCountDown = () => {
  // 先清除旧的定时器
  if (countDownInterval) {
    clearInterval(countDownInterval);
  }
  // 设置新的定时器
  countDownSeconds.value = 60;
  btnText.value = `${countDownSeconds.value}s`;
  countDownInterval = setInterval(() => {
    countDownSeconds.value--;
    if (countDownSeconds.value <= 0) {
      clearInterval(countDownInterval as NodeJS.Timer);
      btnDisabled.value = false;
      btnText.value = "获取验证码";
    } else {
      btnText.value = `${countDownSeconds.value}s`;
    }
  }, 1000);
};
</script>

